package com.pxxy.mall.product.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.pxxy.mall.product.entity.CategoryEntity;
import com.pxxy.mall.product.service.CategoryService;
import com.pxxy.mall.product.vo.Catalog2Vo;
import lombok.AllArgsConstructor;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.awt.peer.CanvasPeer;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author zhangjj
 * @since 2024/1/16
 */
@Controller
@AllArgsConstructor
public class IndexController {

    private StringRedisTemplate redisTemplate;


    private CategoryService categoryService;

    private RedissonClient redisson;


    @GetMapping({"/", "index.html"})
    public String toIndex(Model model) {
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categorys", categoryEntities);
        return "index";
    }


    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catalog2Vo>> getCatelogJson() {
        Map<String, List<Catalog2Vo>> map = categoryService.getCatelogJson();
        return map;
    }






















    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        RLock rLock = redisson.getLock("hello");
        rLock.lock();
        try {
            System.out.println("加锁成功，执行业务代码..." + Thread.currentThread().getId());
            Thread.sleep(40000);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            System.out.println("释放锁");
            rLock.unlock();
        }
        return "hahha";

    }


    /**
     * 测试setnx
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/testSetNx")
    public CategoryEntity testSetNx() {
        String entity = redisTemplate.opsForValue().get("category");
        if (!StringUtils.isEmpty(entity)) {
            System.out.println("用了缓存");
            CategoryEntity parse = JSON.parseObject(entity, CategoryEntity.class);
            return parse;
        }
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        if (lock) {
            String entity1 = redisTemplate.opsForValue().get("category");
            if (!StringUtils.isEmpty(entity1)) {
                CategoryEntity parse = JSON.parseObject(entity, CategoryEntity.class);
                return parse;
            }
            CategoryEntity category = categoryService.getById(1);
            if (category != null) {
                String categoryJson = JSON.toJSONString(category);
                redisTemplate.opsForValue().set("category", categoryJson, 30, TimeUnit.SECONDS);

                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then " +
                        "return redis.call('del',KEYS[1]) else return 0 end";
                String lock1 = redisTemplate.opsForValue().get("lock");
                if (uuid.equals(lock1)) {
                    //删除锁
                    redisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
                            Arrays.asList("lock"), uuid);
                    System.out.println("删除锁成功");
                }
                return category;
            } else {
                return null;
            }
        } else {
            return testSetNx();
        }
    }


    /**
     * 测试redisson
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/testRedisson")
    public CategoryEntity testRedisson() {
        String entity = redisTemplate.opsForValue().get("category");
        if (!StringUtils.isEmpty(entity)) {
            System.out.println("用了缓存");
            CategoryEntity parse = JSON.parseObject(entity, CategoryEntity.class);
            return parse;
        }
        Config config = new Config();
        config.useSingleServer().setAddress("redis://192.168.10.133:6379");
        RedissonClient redisson = Redisson.create(config);
        RLock lock = redisson.getLock("lock");
        lock.lock();  //看门狗机制加锁

        CategoryEntity category = null;
        try {
            category = categoryService.getById(1);
            if (category != null) {
                System.out.println("加入缓存");
                String categoryJson = JSON.toJSONString(category);
                redisTemplate.opsForValue().set("category", categoryJson, 30, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
        return category;
    }


}
